package com.bjian.CodeSandBox.codeSandbox.impl;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.bjian.CodeSandBox.codeSandbox.CodeSandBoxTemplate;
import com.bjian.CodeSandBox.codeSandbox.CodeSandbox;
import com.bjian.CodeSandBox.codeSandbox.model.ExecuteCodeRequest;
import com.bjian.CodeSandBox.codeSandbox.model.ExecuteCodeResponse;
import com.bjian.CodeSandBox.codeSandbox.model.JudgeInfo;
import com.bjian.CodeSandBox.unitl.ProcessUtil;
import com.bjian.CodeSandBox.unitl.model.ExeuteMessage;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import org.springframework.stereotype.Component;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 使用docker实现代码沙箱
 */
@Component
public class DockerCodeSandboxImpl extends CodeSandBoxTemplate {
    @Override
    public boolean cleanRunFile(File userCodeFile){
        boolean del = true;
        if (userCodeFile.getParentFile() != null) {
//            System.out.println(userCodeFile.getParent());
            del = FileUtil.del(userCodeFile.getParent());
            System.out.println("删除" + (del ? "成功" : "失败"));
        }
        return del;
    }

    @Override
    public List<ExeuteMessage> runCodeFile(File userCodeFile,List<String> inputList) {
        List<ExeuteMessage> exeuteMessageList = new ArrayList<>();
        //创建docker操作类
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        String cmd = "openjdk:8-alpine";
        //创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(cmd);
        HostConfig hostConfig = new HostConfig();//运行程序的参数配置类
        hostConfig.withMemory(100 * 1000 * 1000L);
        hostConfig.withMemorySwap(0l);
        hostConfig.withCpuCount(1L);
        hostConfig.setBinds(new Bind(userCodeFile.getParent(), new Volume("/app")));//代码目录文件路径映射
        CreateContainerResponse exec = containerCmd
                .withHostConfig(hostConfig)
                .withNetworkDisabled(true)
                .withReadonlyRootfs(true)
                .withAttachStderr(true)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withTty(true)
                .exec();

        System.out.println(exec);
        String containerId = exec.getId();//容器id
        //启动容器
        dockerClient.startContainerCmd(containerId).exec();
        //循环执行命令
        final int[] tempi = {0};
        for (String inputArgs : inputList) {
            StopWatch stopWatch = new StopWatch();
            String[] inputArgsList = inputArgs.split(" ");
            ExeuteMessage exeuteMessage = new ExeuteMessage();
            // docker exec keen_blackwell java -cp /app Main 1 3
            String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, inputArgsList);
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            //System.out.println("创建执行命令：" + execCreateCmdResponse);

            String execId = execCreateCmdResponse.getId();
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onNext(Frame frame) {//回调函数，输出结果
                    StreamType streamType = frame.getStreamType();
                    String str = new String(frame.getPayload());
                    if (StreamType.STDERR.equals(streamType)) {
                        exeuteMessage.setExitValue(-1);
                        exeuteMessage.setErrorMessage("错误输出：" + str);
                    } else {
                        exeuteMessage.setExitValue(0);
                        System.out.print("----------测试----------");
                        System.out.print(str.split("\n")[0]);
                        System.out.print("----------测试----------");
                        exeuteMessage.setMessage(str.split("\n")[0]);
                    }
                    super.onNext(frame);
                }
            };
            // 获取容器的统计信息
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            ResultCallback<Statistics> statisticsResultCallback = new ResultCallback<Statistics>() {
                @Override
                public void onNext(Statistics statistics) {
                    //System.out.println("内存占用：" + statistics.getMemoryStats().getUsage());
                }

                @Override
                public void close() throws IOException {

                }

                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }
            };

            try {
                statsCmd.exec(statisticsResultCallback);
                stopWatch.start();
                dockerClient.execStartCmd(execId)
                        .exec(execStartResultCallback)
                        .awaitCompletion();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            finally {
                statsCmd.close();
            }
            stopWatch.stop();
            exeuteMessage.setRunTime(stopWatch.getLastTaskTimeMillis());
            System.out.println("执行时间："+stopWatch.getLastTaskTimeMillis());
            exeuteMessageList.add(exeuteMessage);
        }
        return exeuteMessageList;
    }




}
